package com.ruoyi.web.controller.api.recipe;

import com.ruoyi.api.domain.recipe.FeedbackEntity;
import com.ruoyi.common.annotation.NoLoginRequired;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recipe.domain.RecipeFeedback;
import com.ruoyi.recipe.service.IRecipeFeedbackService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.APIController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api("反馈意见")
@RestController
@RequestMapping("/api/feedback")
@NoLoginRequired
public class FeedbackController extends APIController {

    @Autowired
    private IRecipeFeedbackService feedbackService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation("提交反馈意见")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "contentText", value = "反馈内容", required = true, dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/add")
    public AjaxResult addSave(FeedbackEntity entity) {
        if (StringUtils.isEmpty(entity.getOpenId())) return error("微信openId不能为空");
        if (StringUtils.isEmpty(entity.getContentText())) return error("反馈内容不能为空");

        SysUser user = userService.selectUserByOpenId(entity.getOpenId());
        if (user == null) return error("用户不存在");

        RecipeFeedback feedback = new RecipeFeedback();
        feedback.setOpenId(entity.getOpenId());
        feedback.setContentText(entity.getContentText());
        feedback.setStatus("0");
        feedback.setUserId(user.getUserId());
        feedback.setCreateBy(user.getLoginName());

        RecipeFeedback latestFeedback = feedbackService.selectLatestRecipeFeedback(feedback);
        // 判断时间是否大于5秒
        if (latestFeedback != null && System.currentTimeMillis() - latestFeedback.getCreateTime().getTime() < 5000) {
            return error("请勿频繁提交反馈");
        }

        int rtn = feedbackService.insertRecipeFeedback(feedback);
        if (rtn > 0) return success("反馈成功");
        return error("反馈失败");
    }
}
